import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { base, createPage, ajax, getMultiLang } from 'nc-lightapp-front';
const { NCDiv, EmptyAreaTip } = base;
import { initTemplate } from './events';
import './index.less';
import SelfDocTable from '../table';
import SelfExecute from '../search';
const treeRootId = 'selfPlan';

class SyncTree extends Component {
	constructor(props) {
		super(props);
		this.props = props;
		let { syncTree } = this.props;
		let { setSyncTreeData } = syncTree;
		this.setSyncTreeData = setSyncTreeData; //设置树根节点数据方法
		let data = [];
		this.newTree = syncTree.createTreeData(data); //创建树 组件需要的数据结构
		this.state = {
			pk_accountingbook: '',
			selectedValue: '', //树选中
			saveData: {},
			stateType: '1',
			tableData: [], //表格数据
			appcode: this.props.getSearchParam('c'),
			pagecode: this.props.getSearchParam('p'),
			cardEmpty: false, //树空省适配 右半部分是否显示提示卡片
            rightEmptyDom: false, //右半部分是否显示默认内容
			json: {}
		};
		this.datapool = {
			treeData: [],
			tableData: []
		};
	}
	// componentWillMount() {
	// 	// this.getInitData()
	// 	let localurl = decodeURIComponent(window.location);
	// 	let type;
	// 	if (localurl.match(/type=(\S*)/)) {
	// 		type = localurl.match(/type=(\S*)/)[1];
	// 	}
	// }
	componentWillMount() {
		let localurl = decodeURIComponent(window.location);
		let type;
		if (localurl.match(/type=(\S*)/)) {
			type = localurl.match(/type=(\S*)/)[1];
		}
		let callback= (json) =>{
			this.setState({
				json:json,
			},()=>{		  
				initTemplate.call(this, this.props);
			})
		}
		getMultiLang({moduleId:'20020SDTPEPAGE',domainName:'gl',currentLocale:'simpchn',callback});
	}
	componentDidMount() {}
	//获取初始数据
	getInitData = (pk) => {
		let data = {
			pk_accountingbook: pk ? pk : '' //核算账簿主键
		};
		this.setState({
			pk_accountingbook: pk
		});
		if (!pk) {
			this.datapool.treeData = [];
			this.datapool.tableData = [];
			this.refresh();
		}
		let url = '/nccloud/gl/voucher/queryTransProjTree.do';
		ajax({
			url,
			data,
			success: (response) => {
				let { data, error, success } = response;
				if (success) {
					this.setState({
						mainData: data ? data : [],
						cardEmpty: data ? false : true,
            			rightEmptyDom: data ? true : false, 
						selectedValue: '',
					});
					this.datapool.treeData = data ? this.dealTreeData(data) : [];
					this.datapool.tableData = [];
					this.refresh();
					this.SelfExecute.setButtonDisabled(!data)
				} else {
				}
			}
		});
	};

	onSelectEve = (data, item, isChange) => {
		let url = '/nccloud/gl/voucher/queryTransProjDef.do';
		let sendData = { pk_accountingbook: this.state.pk_accountingbook, pk_transproj: data };
		this.setState({
			selectedValue: data
		});
		let tableData = [];
		ajax({
			url,
			data: sendData,
			success: (response) => {
				const { data, error, success } = response;
				if (success && data) {
					tableData = data;					
				}
				this.datapool.tableData = tableData;
				this.setState({ 
					tableData,
					cardEmpty: false, 
            		rightEmptyDom: true,
				});
			}
		});
	}

	getCheckedData() {
		let checkedData = this.SelfDocTable.getCheckedData();
		return checkedData;
	}
	getPK = (data) => {
		//获取选中账簿
		this.getInitData(data);
	};
	dealTreeData(data) {
		//去null
		let deleteDataChildrenProp = function(node) {
			if (!node.children || node.children.length == 0) {
				delete node.children;
			} else {
				node.isLeaf = false;
				node.children.forEach((e) => {
					deleteDataChildrenProp(e);
				});
			}
		};

		let joinCodeAndName = function(node){
			if(node){
				node.title = node.innercode + " " + node.refname;
				node.refname = node.innercode + " " + node.refname;
				if(node.children){
					node.children.map((item) => {
						joinCodeAndName(item);
						return item;
					});
				}
			}
		}
		if (data) {
			data.forEach((e) => {
				deleteDataChildrenProp(e);
				joinCodeAndName(e);
			});
		}
		return data;
	}
	getSelectDetails = (data) => {
		let { selectedValue } = this.state;
		let obj = {};
		let localArr = [];
		if (data.length > 0) {
			data.map((item, index) => {
				item.exeno = index + 1;
				item.pk_transproj = selectedValue;
				item.isEdit = true;
				localArr.push(JSON.parse(JSON.stringify(item)));
			});
		}
		this.setState({
			tableData: localArr
		});
	};
	getEditTableData = (data) => {
		this.setState({
			tableData: data
		});
	};

	refresh = () => {
		let page = this;
		let { tableData, treeData } = page.datapool;
		page.setSyncTreeData(treeRootId, treeData);
		page.setState({ tableData, treeData });
	};
	updateButtonStatus(disabled) {
		this.SelfExecute.updateButtonStatus(disabled)
	}
	render() {
		const { syncTree, DragWidthCom } = this.props;
		let { createSyncTree } = syncTree;
		// let tableColumns = this.getTableColumns()
		let { pk_accountingbook, tableData, selectedValue, cardEmpty, rightEmptyDom, json } = this.state;
		let emptyTipTxt = pk_accountingbook ? json['20020SDTPEPAGE-000018'] : json['20020SDTPEPAGE-000019']; //'请先到自定义结转方案档案定义节点增加档案' : '请先选择财务核算账簿'
		return (
			<div className='nc-bill-tree-table'>
				<SelfExecute
					getPK={this.getPK.bind(this)}
					getCheckedData={this.getCheckedData.bind(this)}
					selectedValue={selectedValue}
					onSelectEve={this.onSelectEve.bind(this)}
					pk_accountingbook={pk_accountingbook}
					getSelectDetails={this.getSelectDetails.bind(this)}
					tableData={tableData}
					getEditTableData={this.getEditTableData.bind(this)}
					onAccountingbookSelect={this.getInitData}
					pagecode={this.state.pagecode}
					appcode={this.state.appcode}
					SelfExecuteRef={(init) => {this.SelfExecute = init;}}
				/>
				<div className="tree-table">
					<DragWidthCom
						defLeftWid={'280px'}
						leftDom={
							<div className='tree-area'>
								{createSyncTree({
									treeId: treeRootId,
									showLine: true,
									showModal: false, //是否使用弹出式编辑
									needSearch: false, //是否需要查询框，默认为true,显示。false: 不显示
									needEdit: false,
									selectedForInit: true, //默认选中第一个子节点
									onSelectEve: this.onSelectEve.bind(this) //选择节点回调方法
								})}
							</div>
						}
						rightDom={
							<div style={{ height: '100%' }}>
                            	{/* mptyAreaTip type值为"desc"/"btn","desc"状态无下方按钮，且仅设置btn的时候可以添加onClick回调 */}
                                <EmptyAreaTip type='desc' desc={emptyTipTxt}
									// onClick={this.onAddAccsysClass} 
								show={cardEmpty} />
                                
                                <div style={{height: "100%", display: rightEmptyDom ? 'block' : 'none'}}>
									<SelfDocTable
										mainData={tableData}
										// columns = {tableColumns}
										updateButtonStatus={this.updateButtonStatus.bind(this)}
										SelfDocTableRef={(init) => {
											this.SelfDocTable = init;
										}}
									/>
								</div>
							</div>
						}
					/>
				</div>
			</div>
		);
	}
}

SyncTree = createPage({
	// initTemplate: initTemplate
})(SyncTree);
ReactDOM.render(<SyncTree />, document.querySelector('#app'));
